package cn.bfay.lion.jingdong.manager;

import cn.bfay.cache.redis.RedisKeyBuilder;
import cn.bfay.cache.redis.RedisTime;
import cn.bfay.cache.redis.RedisUtils;
import cn.bfay.lion.jingdong.redis.RedisKeyTemplate;
import cn.bfay.web.exception.BizException;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import jd.union.open.promotion.common.get.request.PromotionCodeReq;
import jd.union.open.promotion.common.get.request.UnionOpenPromotionCommonGetRequest;
import jd.union.open.promotion.common.get.response.UnionOpenPromotionCommonGetResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * JfManager.
 *
 * @author wangjiannan
 */
@Slf4j
@Component
public class JfManager {
    private static final String SERVER_URL = "https://router.jd.com/api";
    private static final int JF_SUCCESS_CODE = 200;

    /**
     * 联盟分配给应用的app_key
     */
    @Value("${jingfen.app.key}")
    private String appKey;
    @Value("${jingfen.app.secret}")
    private String appSecret;
    /**
     * 根据API属性标签，如果需要授权，则此参数必传;如果不需要授权，则此参数不需要传 N
     */
    @Value("${jingfen.access.token}")
    private String accessToken;
    /**
     * 站点ID是指在联盟后台的推广管理中的网站Id、APPID.
     * 1、通用转链接口禁止使用社交媒体id入参；
     * 2、订单来源，即投放链接的网址或应用必须与传入的网站ID/AppID备案一致，否则订单会判“无效-来源与备案网址不符”
     */
    @Value("${jingfen.site.id}")
    private String siteId;
    @Value("${jingfen.debug:false}")
    private Boolean jfDebug;

    /**
     * 获取通用推广链接.
     *
     * @param skuid skuid
     * @return string
     */
    public String getPromotionCommon(String skuid) {
        String materialId = "https://item.m.jd.com/product/" + skuid + ".html";
        if (jfDebug) {
            return materialId;
        }
        String redisKey = RedisKeyBuilder.generateRedisKey(RedisKeyTemplate.PROMOTION_COMMON_TEMPLATE, skuid);
        try {
            // 缓存中查找
            String url = RedisUtils.getValue(redisKey);
            if (StringUtils.isNotBlank(url)) {
                return url;
            }
            // 缓存中不存在，调用接口
            JdClient client = new DefaultJdClient(SERVER_URL, accessToken, appKey, appSecret);
            UnionOpenPromotionCommonGetRequest request = new UnionOpenPromotionCommonGetRequest();
            PromotionCodeReq promotionCodeReq = new PromotionCodeReq();
            promotionCodeReq.setMaterialId(materialId);
            promotionCodeReq.setSiteId(siteId);
            request.setPromotionCodeReq(promotionCodeReq);
            UnionOpenPromotionCommonGetResponse response = client.execute(request);
            log.info("获取商品{}推广链接result={}", skuid, response.getSysOriginalMsg());
            if (response.getCode() != JF_SUCCESS_CODE) {
                throw new BizException(String.valueOf(response.getCode()), response.getMessage());
            }
            url = response.getData().getClickURL();
            RedisUtils.setValue(redisKey, url, RedisTime.WEEK);
            return url;
        } catch (Exception e) {
            log.error("获取商品{}推广链接异常", skuid, e);
            RedisUtils.setValue(redisKey, materialId, RedisTime.DAY);
            return materialId;
        }
    }
}
